/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.address;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;

import javax.sip.address.URI;
import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public abstract class URIParserBase<T extends URI> implements URIParser<T> {

    protected abstract Log getLogger();

    public T parse(byte[] uri, int start, int end) throws ParseException {
        return parse(uri, start, end, null);
    }

    protected void parseParameters(byte[] data, int start, int end, URIBase uriObject) throws ParseException {
        int pos = start, prevPos = data[start] == ';' ? start : start - 1;
        while ((pos = ByteArrayUtil.firstOccurence(data, ';', prevPos + 1, end)) != -1 || prevPos < end) {
            if (pos == -1) pos = end;
            final int index = ByteArrayUtil.firstOccurence(data, '=', prevPos + 1, pos);
            if (index != -1)
                uriObject.setParameter(new String(data, prevPos + 1, index - prevPos - 1), new String(data, index + 1, pos - index - 1));
            else
                uriObject.setParameter(new String(data, prevPos + 1, pos - prevPos - 1), null);
            prevPos = pos;
        }
    }

    protected void parseHeaders(byte[] data, int start, int end, URIBase uriObject) throws ParseException {
        int pos = start, prevPos = data[start] == '&' ? start : start - 1;
        while ((pos = ByteArrayUtil.firstOccurence(data, '&', prevPos + 1, end)) != -1 || prevPos < end) {
            if (pos == -1) pos = end;
            final int index = ByteArrayUtil.firstOccurence(data, '=', prevPos + 1, pos);
            if (index != -1)
                uriObject.setHeader(new String(data, prevPos + 1, index - prevPos - 1), new String(data, index + 1, pos - index - 1));
            else
                uriObject.setHeader(new String(data, prevPos + 1, pos - prevPos - 1), null);
            prevPos = pos;
        }
    }

    protected void fail(String message, int offset) throws ParseException {
        getLogger().error(message);
        throw new ParseException(message, offset);
    }
}
/*
 * $Log$
 */